module MetaUtilities where
import FlsParser
import Data.Bson
import Data.Time.Clock.POSIX
import qualified Data.ByteString.Char8 as B
import Data.List(foldl')

--Need to move this stuff, to datatype def in FlsParser.hs
inodeToString (Inode num attr sub) = (show num) ++ "-" ++ (show attr) ++ "-" ++ (show sub)
inodeToString (EmptyInode s) = B.unpack s

fileTypeToString ft = (fnStruct ft):'/':(metaStruct ft):""

filePermsToString (FP ow g ot) = (permsToString ow) ++ (permsToString g) ++ (permsToString ot)

permsToString :: Perms -> String
permsToString p = r_:w_:x_:""
	where
          r_ = if (FlsParser.read p) then 'r' else '-'
          w_ = if (write p) then 'w' else '-'
          x_ = if (exec p) then 'x' else '-'

--it looks like fls auto converts things to unix time.. so we shouldn't have to convert
convertTimeStampUTC t = posixSecondsToUTCTime(fromIntegral t :: POSIXTime)
--unixTimeOffset = (369 * 365 + 89) * 24 * 3600 * 10000000


--Json lists don't have quotes
showJson :: Document -> String
showJson doc = "{" ++ fields ++ "}"
    where
        fields :: String
        fields = foldl' (fieldToString) "" doc
        fieldToString :: String -> Field -> String
        fieldToString "" field = showField' field
        fieldToString acc field = showString acc (showString (',': (showField' field)) "")
        showField' field = show (label field) ++ ":" ++ (show (value field))

showJson' :: Document -> String
showJson' doc = "{" ++ fields ++ "}"
    where
        fields = foldl' (step) "" doc
        step :: String -> Field -> String
        step "" field = showField field
        step acc field = showString acc (showString (',': (showField field)) "")
        showField f = (show (label f)) ++ ":" ++ (showValue (value f))
        showValue v = case v of
	        Float x -> show x
	        String x -> show x
	        Doc x -> showJson' x
	        Array x -> show x
	        Bin x -> show x
	        Fun x -> show x
	        Uuid x -> show x
	        Md5 x -> show x
	        UserDef x -> show x
	        ObjId x -> show x
	        Bool x -> show x
	        UTC x -> "\"" ++ (show x) ++ "\""
	        Null -> ""
	        RegEx x -> show x
	        JavaScr x -> show x
	        Sym x -> show x
	        Int32 x -> show x
	        Int64 x -> show x
	        Stamp x -> show x
	        MinMax x -> show x
